const express = require('express');
const router = express.Router();
const { sendResponse } = require('@/utils/tool')
const { getRoutesByRoleId, bindRolesAndRoutes } = require("@/services/route.services")

/**
 * @swagger
 * /getRoutesByRoleId/{id}:
 *   get:
 *     summary: 获取路由列表
 *     description: 通过角色ID获取路由列表
 *     tags: [路由]
 *     security:
 *       - authorization: []
 *     parameters:
 *       - 
 *         in: path
 *         name: id
 *         description: 角色id
 *         required: true
 *     responses:
 *       200:
 *         description: 请求成功
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       401:
 *         $ref: '#/components/responses/unauthorized'
 *       500:
 *         $ref: '#/components/responses/error'
 */
router.get('/getRoutesByRoleId/:roleId', async (req, res) => {
  try {
    let { roleId } = req.params
    let result = await getRoutesByRoleId(roleId)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500, msg: error })
  }
})


/**
 * @swagger
 * /bindRolesAndRoutes:
 *   post:
 *     summary: 绑定角色和路由
 *     description: 绑定角色和路由
 *     tags: [路由]
 *     security:
 *       - authorization: []
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               roleId:
 *                 type: string
 *                 description: 角色id
 *                 example: 1
 *                 required: true
 *               routeIds:
 *                 type: array
 *                 description: 路由id数组
 *                 example: '[1,2,3]'
 *                 required: true
 *     responses:
 *       200:
 *         description: 请求成功
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       401:
 *         $ref: '#/components/responses/unauthorized'
 *       500:
 *         $ref: '#/components/responses/error'
 */
router.post('/bindRolesAndRoutes', async (req, res) => {
  try {
    let { roleId, routeIds } = req.body
    if (!Array.isArray(routeIds)) {
      routeIds = routeIds && JSON.parse(routeIds)
    }
    let result = await bindRolesAndRoutes(roleId, routeIds)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500, msg: error })
  }
})

module.exports = router